//***定义为全局变量***
//获取驱动信息
var driver = JSON.parse($("#dirverJson").text());

// 显示驱动数据源和目标源
function showDriverEditInfo(driver) {
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.targetMapping;

	// 获取数据源和目标源连接器logo
	var sourceLogo = getDriverLogo(sourceMapping);
	var targetLogo = getDriverLogo(targetMapping);
	$("#sourceLogo").attr("src", sourceLogo);
	$("#targetLogo").attr("src", targetLogo);

	// 获取数据源和目标源连接器类型
	var sourceType = DriverConnectorConstant[sourceMapping.connector]['type'];
	var targetType = DriverConnectorConstant[targetMapping.connector]['type'];
	$("#sourceType").text("类型：" + sourceType);
	$("#targetType").text("类型：" + targetType);

}

// 显示驱动编辑配置（迁移/同步）
function showDriverEditConfig(opr) {
	var url = '';
	switch (opr) {
	case 'migration':
		url = $basePath + "/driver/page/driverEditMigration";
		break;
	case 'sync':
		url = $basePath + "/driver/page/driverEditSync";
		break;
	default:
		break;
	}
	if ('' != url) {
		$.post(url, function(resp) {
			// 加载后端响应视图
			$("#driverEditConfigContainer").html(resp);
		});
	}
}

// 绑定修改驱动同步方式切换事件
function bindEventForDriverEditConfig($driverEditConfigChange, driver) {
	// 初始化icheck插件
	$driverEditConfigChange.find("input").iCheck({
		labelHover : false,
		cursor : true,
		radioClass : 'iradio_flat-blue',
	}).on('ifChecked', function(event) {
		showDriverEditConfig($(this).val());
	});

	var model = 'all' == driver.model ? 0 : 1;
	// 默认渲染数据迁移配置
	$driverEditConfigChange.find("input").eq(model).iCheck("check");

	// 如果是webservice连接器，隐藏数据迁移radio
	if (driver.sourceMapping.connector != ConnectorConstantWebService) {
		$(".driverEditRadioDisplay").removeClass("hidden");
	} else {
		$(".driverEditSyncRadioDisplay").removeClass("hidden").after('<div class="col-sm-2"></div>');
	}
}

// 获取基本信息
function saveDriverConfigCommonProperty(driver) {
	var trs = $("#propertyList").find("tr");
	var sourceFileds = [];
	var targetFileds = [];
	trs.each(function(i, o) {
		var sField = $(this).find("td:eq(0)");
		var tField = $(this).find("td:eq(1)");
		sourceFileds.push({
			"name" : sField.text(),
			"type" : sField.attr("type"),
			"typeName" : sField.attr("typeName")
		});
		targetFileds.push({
			"name" : tField.text(),
			"type" : tField.attr("type"),
			"typeName" : tField.attr("typeName")
		});
	});
	driver.sourceMapping.fileds = sourceFileds;
	driver.targetMapping.fileds = targetFileds;
}

// 获取过滤条件
function saveDriverConfigCommonFilter(driver) {
	// 过滤条件
	var ands = [];
	var ors = [];
	var trs = $("#conditionList").find("tr");
	trs.each(function(i, o) {
		var combination = $(this).find("td:eq(0)").attr('name');
		var name = $(this).find("td:eq(1)").attr('name');
		var operator = $(this).find("td:eq(2)").attr('name');
		var value = $(this).find("td:eq(3)").attr('name');
		if ("and" == combination) {
			ands.push({
				"name" : name,
				"operator" : operator,
				"value" : value
			});
		} else if ("or" == combination) {
			ors.push({
				"name" : name,
				"operator" : operator,
				"value" : value
			});
		}
	});
	driver.query = {};
	driver.query.and = ands;
	driver.query.or = ors;
}

// 获取数据迁移配置
function saveDriverConfigMigration(driver) {
	// 组装基本信息配置
	saveDriverConfigCommonProperty(driver);
	// 组装过滤条件配置
	saveDriverConfigCommonFilter(driver);
	// 设置为迁移
	driver.model = "all";

	// 转换策略
	var classImpl = $("#sourceStrategyConvertRule option:selected").val();
	driver.policy.convert = ""==classImpl ? null : {"className" : classImpl};
	
	// 批量策略
	driver.maxTask = $("#dirverEditMaxTask").val();
	driver.batchNum = $("#dirverEditBatchNum").val();
	driver.threadNum = $("#dirverEditThreadNum").val();
}

// 获取数据同步增量配置,如果校验失败返回false
function saveDriverConfigSyncStrategy(driver) {
	// 校验表单
	if ($("#syncConfigContainer").formValidate() == false) {
		return false;
	}
	// 清空默认策略
	driver.policy = {};
	// 是否开启
	var $enable = $('#sourceStrategyIncrementEnable').val();
	// 增量模式
	var $model = $('#sourceStrategyIncrementModel').find("input:checked").val();
	// 连接器类型
	var conn = driver.sourceMapping.connector;
	var isReturn = false;
	switch (conn) {
	case ConnectorConstantMysql:
		// 保存Mysql
		driver.policy.increment = {"type" : "mysql"};
		break;
	case ConnectorConstantOracle:
		// 保存Oracle
		driver.policy.increment = {
			"type" : "oracle",
			"dictionary" : $("#sourceStrategyIncrementDictionaryPath").val()
		};
		break;
	case ConnectorConstantSqlMysql:
		// 保存SqlMysql
		driver.policy.increment = {
			"type" : "sqlMysql",
			"table" : $("#sourceStrategyIncrementTable").val(),
			"tableLabel" : $("#sourceStrategyIncrementTableLabel").val()
		};
		break;
	case ConnectorConstantSqlOracle:
		// 保存SqlOracle
		driver.policy.increment = {
			"type" : "sqlOracle",
			"dictionary" : $("#sourceStrategyIncrementDictionaryPath").val()
		};
		break;
	case ConnectorConstantSqlServer:
		// 保存Sqlserver
		driver.policy.increment = {"type" : "sqlserver"};
		break;
	case ConnectorConstantLdap:
		// 保存Ldap
		driver.policy.increment = {"type" : "ldap"};
		break;
	case ConnectorConstantWebService:
		// 保存Webservice
		driver.policy.increment = {
			"enable" : $enable,
			"model" : 'log',
			"type" : "ws"
		};
		isReturn = true;
		break;
	default:
		break;
	}
	// 判断是否继续往下配置
	if(isReturn){
		return true;
	}

	// 增量策略
	driver.policy.increment.enable = $enable;
	driver.policy.increment.model = $model;
	if ('quartz' == $model) {
		var $quartzCron = $('#sourceStrategyQuartzCron').val();
		var $quartzFiled = $('#sourceStrategyQuartzFiled').val();
		var $quartzEvent = $("#sourceStrategyQuartzEvent").val();
		var $quartzEventInsert = $("#sourceStrategyQuartzEventInsert").val();
		var $quartzEventUpdate = $("#sourceStrategyQuartzEventUpdate").val();
		var $quartzEventDelete = $("#sourceStrategyQuartzEventDelete").val();
		var $sourceStrategyIncrementTableLabel = $("#sourceStrategyIncrementTableLabel").val();
		var $quartzScnPos = $("#sourceStrategyQuartzScnPos").val();
		// 增量字段和事件字段不能为空
		if (null == $quartzFiled || undefined == $quartzFiled || null == $quartzEvent || undefined == $quartzEvent) {
			bootGrowl("定时配置不能为空!", "danger");
			return false;
		}
		driver.policy.increment.quartzCron = $quartzCron;
		driver.policy.increment.quartzFiled = $quartzFiled;
		driver.policy.increment.quartzEvent = $quartzEvent;
		driver.policy.increment.quartzEventInsert = $quartzEventInsert;
		driver.policy.increment.quartzEventUpdate = $quartzEventUpdate;
		driver.policy.increment.quartzEventDelete = $quartzEventDelete;
		driver.policy.increment.tableLabel = $sourceStrategyIncrementTableLabel;
		driver.policy.increment.scnPos = $quartzScnPos;
	}

	// 转换策略
	driver.policy.convert = { "className" : $("#sourceStrategyConvertRule option:selected").val() };
	return true;
}

// 获取数据同步配置,如果校验失败返回false
function saveDriverConfigSync(driver) {
	// 组装基本信息配置
	saveDriverConfigCommonProperty(driver);
	// 组装过滤条件配置
	saveDriverConfigCommonFilter(driver);
	// 组装策略配置
	if (!saveDriverConfigSyncStrategy(driver)) {
		return false;
	}
	// 设置为同步
	driver.model = "increment";
}

// 保存驱动配置
function saveDriverConfig(id, driver) {
	id = id.find("input[name='driverEditConfig']:checked").val();
	switch (id) {
	// 数据迁移
	case 'migration':
		//对迁移配置表单进行必填校验
		if($("#migrationConfigContainer").formValidate()==false){
			return false;
		}
		saveDriverConfigMigration(driver);
		break;
	// 数据同步
	case 'sync':
		// 校验数据同步高级配置，返回null意味着校验失败
		if (saveDriverConfigSync(driver) == false) {
			bootGrowl("保存失败,请检查参数.", "danger");
			return false;
		}
		break;
	default:
		break;
	}
	
	// 保存驱动配置
	$.loadingT(true);
	$.post($basePath + "/driver/update", {
		"mapping" : JSON.stringify(driver)
	}, function(data) {
		$.loadingT(false);
		if (data.success == true) {
			bootGrowl(data.resultValue, "success");
			$initContainer.load($basePath + "/index");
		} else {
			bootGrowl(data.resultValue, "danger");
		}
	});
}

$(function() {
	// 显示驱动编辑信息
	showDriverEditInfo(driver);

	// 加载数据迁移
	var $driverEditConfigChange = $('#driverEditConfigChange');
	bindEventForDriverEditConfig($driverEditConfigChange, driver);

	// 保存
	$("#driverSubBtn").click(function() {
		saveDriverConfig($driverEditConfigChange, driver);
	});
	// 返回
	$("#driverBackIndexBtn").click(function() {
		// 加载页面
		$initContainer.load($basePath + "/index");
	});
})